package com.laikan.reader.bookreader.activity;

import android.content.Intent;
import android.graphics.Paint;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.bookfriend.activity.RechargePage;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.utils.LoadingDialog;
import com.laikan.reader.database.Book;
import com.laikan.reader.database.DBBook;
import com.socks.library.KLog;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class DesBookBuy extends BasicActivity implements OnClickListener {

    private TextView title, name, dis_price, full_price, balance, sure, cancel;
    private LinearLayout linear;
    private String bookid;
    private View zhezhao;
    private boolean SureFlag = false;
    private RelativeLayout long_item;
    private BaseDataBean result;
    private Book bookDes;
    private String chid = "";
    private int goInType;
    private LoadingDialog mloadingDialog;
    private int typeRef;

    @Override
    protected void assignViews() {
        setContentView(R.layout.lk_des_group);
        title = (TextView)findViewById(R.id.rl_title);
        name = (TextView)findViewById(R.id.name);
        dis_price = (TextView)findViewById(R.id.dis_price);
        full_price = (TextView)findViewById(R.id.full_price);
        balance = (TextView)findViewById(R.id.balance);
        linear = (LinearLayout)findViewById(R.id.linear);
        zhezhao = findViewById(R.id.bg_view);
        sure = (TextView)findViewById(R.id.sure);
        cancel = (TextView)findViewById(R.id.cancel);
        long_item = (RelativeLayout)findViewById(R.id.long_item);
    }

    @Override
    protected void initData() {
        mloadingDialog = new LoadingDialog(mContext);
        Intent intent = getIntent();
        goInType = intent.getIntExtra("goInType", 3);
        chid = intent.getStringExtra("chid");
        typeRef = intent.getIntExtra("typeRef", -1);
        String fullPrice = intent.getStringExtra("fullPrice");
        String bookname = intent.getStringExtra("bookName");
        String discountPrice = intent.getStringExtra("discountPrice");
        bookid = intent.getStringExtra("bookId");
        bookDes = (Book)getIntent().getSerializableExtra("bookDes");
        name.setText(bookname);
        if (TextUtils.isEmpty(discountPrice) || discountPrice.equals("限免")){
            getQuanbenPrice();
        }
        dis_price.setText(discountPrice);
        full_price.setText(fullPrice);
        full_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); ///文本加中划线
    }

    @Override
    protected void setListener() {
        zhezhao.setOnClickListener(this);
        sure.setOnClickListener(this);
        cancel.setOnClickListener(this);
        long_item.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bg_view:
                onBackPressed();
                break;
            case R.id.sure:
                if (!SureFlag) {
                    getDate();
                }else {
                    Intent intent = new Intent(mContext, RechargePage.class);
                    startActivity(intent);
                }
                break;
            case R.id.cancel:
                onBackPressed();
                break;
        }

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(0, R.anim.close);
        finish();
    }

    public void setView(BaseDataBean result) {
        title.setText("提示");
        linear.setVisibility(View.GONE);
        balance.setText(result.getError_msg());
        balance.setVisibility(View.VISIBLE);
        sure.setText("充值");
        SureFlag = true;

    }

    /**
     * 从网络获取数据
     */
    private void getDate() {
        mloadingDialog.show();
        Map<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                mloadingDialog.dismiss();
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean>() {}.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                }catch (Exception e) {
                    e.printStackTrace();
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    return;
                }
                String errorNo = result.getError_no();
                if (result.getResult().equals(Constants.RESULT_OK)) {
                    DBBook.getInstance().insertBook(bookDes);
                    ToastMgr.showShortToast("购买成功");
                    SPUtil.putInt(bookid + chid + "buyback", goInType);
                    if (typeRef != -1) {
                        SPUtil.putBoolean("IsRefer", true);
                        SPUtil.putInt("typeRef", typeRef);
                    }
                    onBackPressed();
                }
                if (Constants.RESULT_BALANCE_NOT_ENOUGH.equals(errorNo) || Constants.RESULT_TICKET_NOT_ENOUGH.equals(errorNo)) {
                    setView(result);
                }else {
                    ToastMgr.showShortToast(result.getError_msg());
                    onBackPressed();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                mloadingDialog.dismiss();
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                KLog.e("网络不给力，请重试。13");
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_desbookbuy + bookid);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_desbookbuy + bookid, map, null, null, requestListener);
    }

    /**
     * 获取全本价格
     */
    private void getQuanbenPrice() {
        Map<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));
        map.put("bookId", bookid);
        map.put("chapterId", 1 + ""); // 查看章节价格,如果是图书那么章节可以传一个任意大于零的整数。
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                try {
                    JSONObject obj = new JSONObject(httpResponse.responseContent);
                    obj.getJSONObject("data").getString("price");
                    String error_msg = obj.getString("error_msg");
                    String result = obj.getString("result");
                    if (Constants.RESULT_OK.equals(result)) {
                        dis_price.setText(obj.getJSONObject("data").getString("price"));
                        full_price.setText(obj.getJSONObject("data").getString("fullPrice"));
                        full_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); ///文本加中划线

                    }else {
                        ToastMgr.showShortToast(error_msg);
                    }
                }catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                mloadingDialog.dismiss();
                ToastMgr.showShortToast(R.string.laikan_data_load_failed);
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_bookchapter_getQuanbenPrice + bookid + "_" + 1 + "");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

        // 90接口,查看章节价格
//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_bookchapter_getQuanbenPrice + bookid + "_" + 1 + "", map, null, null, requestListener);
    }

    @Override
    protected void onDestroy() {

        SPUtil.putBoolean("DoubleVis", false);
        super.onDestroy();
    }
}
